<template>
  <Drawer>
    <BaseForm />
  </Drawer>
</template>
<script lang="tsx" setup>
import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import {
  createDictionary,
  getDictionaryById,
  updateDictionary,
} from '#/api/sys/dictionary';
// 定义 emit 类型
interface Emit {
  (e: 'refresh', data?: any): void;
}
// 创建 emit 函数
const emit = defineEmits<Emit>();
// 定义表单
const [BaseForm, baseFormApi] = useVbenForm({
  showDefaultActions: false, // 不显示操作按钮
  layout: 'vertical',
  schema: [
    {
      component: 'Input',
      fieldName: 'title',
      label: $t('sys.dictionary.displayName'),
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        clearable: true,
      },
      fieldName: 'name',
      label: $t('sys.dictionary.name'),
      rules: 'required',
    },
    {
      component: 'Input',
      fieldName: 'desc',
      label: $t('sys.memberRank.description'),
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      defaultValue: '1',
      componentProps: {
        isButton: true,
        options: [
          {
            label: $t('sys.role.start'),
            value: '1',
          },
          {
            label: $t('sys.role.stop'),
            value: '0',
          },
        ],
      },
      fieldName: 'status',
      label: $t('sys.role.status'),
    },
  ],
});

// 定义弹窗
const [Drawer, drawerApi] = useVbenDrawer({
  // 表单校验
  async onConfirm() {
    const { type, id } = drawerApi.getData<Record<string, any>>();
    // 提交表单
    const isPass = await baseFormApi.validateAndSubmitForm();
    if (!isPass) return; // 校验不通过
    if (type === 'addData') {
      addOrEditDictionaryHandle(isPass);
    }
    if (type === 'editData') {
      addOrEditDictionaryHandle(isPass, id);
    }
    // 校验通过，提交表单
  },
  // 弹窗打开时触发
  async onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { type, id } = drawerApi.getData();
      // 新增打开弹窗时重置表单
      if (type === 'addData') {
        drawerApi.setState({ loading: false, confirmLoading: false });
        baseFormApi.resetForm();
      }
      // 编辑打开弹窗时回显数据
      if (type === 'editData') {
        getDictionaryDetail(id);
      }
    }
  },
});

/**
 * @author Buke
 * @description 新增字典
 * @param {Record<string, any>} formData - 表单数据对象。
 * @param {number} id - 字典ID（可选）。
 * @returns {void}
 */
async function addOrEditDictionaryHandle(
  formData: Record<string, any>,
  id?: number,
): Promise<void> {
  try {
    const data = {
      ...formData,
      id,
      status: Number(formData.status),
    };
    id ? await updateDictionary(data) : await createDictionary(data);
    ElMessage.success('操作成功');
    emit('refresh');
  } catch {
    ElMessage.error('新增失败');
  }
}

/**
 * @author Buke
 * @description 详情数据回显
 * @param {number} id - 要回显的字典ID。
 * @returns {void}
 */
async function getDictionaryDetail(id: number): Promise<void> {
  try {
    drawerApi.setState({ loading: true });
    await getDictionaryById({ id }).then((res: any) => {
      baseFormApi.setValues({
        ...res,
        status: String(res.status),
      });
      // 关闭加载中状态
      drawerApi.setState({ loading: false });
    });
  } catch {
    ElMessage.error('获取详情失败');
    // 关闭加载中状态
    drawerApi.setState({ loading: false });
  }
}
</script>
